import 'dart:async';
import 'dart:ui';

import 'package:cbec_app/components/base/base_badges.dart';
import 'package:cbec_app/components/base/base_icon.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/decoration/decoration_top_nav_bar.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/animation.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_popup/flutter_popup.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class BaseNavBar extends StatefulWidget implements PreferredSizeWidget {
  ///导航栏标题
  final String title;

  ///是否为图标+标题
  final bool isIconTitle;

  ///标题大小
  final double titleSize;

  ///是否为搜索框
  final bool isSearch;

  ///是否显示分享按钮
  final bool isShowShare;

  ///分享按钮回调
  final VoidCallback? shareCallBack;

  ///当点击输入框时需要跳转的路由名称(不传则不跳转)
  final String routeName;

  ///标题颜色
  final Color color;

  ///左侧图标类型
  final IconType iconType;

  ///导航背景颜色
  final Color navBgColor;

  ///是否显示导航底部边框
  final bool isShowNavBottomBorder;

  ///搜索框样式类型
  final SearchStyleType searchType;

  ///输入框是否自动聚焦
  final bool isAutoFocus;

  ///搜索框placeholder
  final String placeholder;

  ///tabbar高度
  final double tabHeight;

  ///tabbar子节点列表
  final List<Widget>? tabChildren;

  ///tabbar背景色
  final Color tabBgColor;

  ///搜索框事件监听
  final void Function(String)? onInput;

  ///自定义导航栏组件
  final Widget? customWidget;

  ///装修
  ///是否为装修导航栏
  final NavType navType;

  ///装修导航配置
  final Map<String, dynamic>? info;

  ///是否显示菜单按钮
  final bool isShowMenuIcon;

  ///导航高度
  final double navHeight;

  ///输入框是否禁用
  final bool isDisable;

  ///阻止默认返回事件
  final VoidCallback? beforeBack;

  ///搜索按钮回调
  final Function(String value)? onClickSearch;

  ///搜索框控制器
  final TextEditingController? textEditingController;

  ///顶部导航栏组件
  BaseNavBar(
      {super.key,
      this.title = '',
      this.titleSize = 14,
      this.isIconTitle = false,
      this.color = Colors.black,
      this.isShowShare = false,
      this.shareCallBack,
      this.isSearch = false,
      this.iconType = IconType.none,
      this.searchType = SearchStyleType.none,
      this.navBgColor = Colors.transparent,
      this.placeholder = '',
      this.tabHeight = 0,
      this.tabChildren = const [],
      this.tabBgColor = Colors.transparent,
      this.onInput,
      this.routeName = '',
      this.isShowNavBottomBorder = false,
      this.isAutoFocus = false,
      this.info,
      this.isShowMenuIcon = false,
      this.navType = NavType.common,
      this.navHeight = 44,
      this.isDisable = true,
      this.beforeBack,
      this.onClickSearch,
      this.customWidget,
      this.textEditingController});

  @override
  State<BaseNavBar> createState() => _BaseNavBarState();

  @override
  Size get preferredSize {
    double borderStyleHeight = 0;
    if (info != null) {
      borderStyleHeight = double.parse(info!['border_style_height'].toString());
    }

    // print('tabHeight ====== $tabHeight');

    return Size(double.infinity, navHeight + (tabHeight ?? 0) + borderStyleHeight);
  }
}

///组件内部状态
class _BaseNavBarState extends State<BaseNavBar> {
  FocusNode focusNode = FocusNode();
  //设置防抖周期
  Duration durationTime = const Duration(milliseconds: 300);
  Timer? timer;

  ///输入框的值
  String inputValue = '';

  @override
  Widget build(BuildContext context) {
    ///留海高度
    final double topPadding = MediaQuery.of(context).padding.top;

    String customColor = widget.info?['style_color_custom_background_color'] ?? '#FFFFFF';

    return Container(
        // margin: EdgeInsets.only(top: topPadding),
        // padding: EdgeInsets.only(top: topPadding),
        width: double.infinity,
        color: widget.navBgColor,
        child: Column(
          children: [
            Container(
              height: topPadding,
              width: double.infinity,
              color: Tools.fromHex(customColor ?? '#FFFFFF'),
            ),

            ///导航栏
            Expanded(child: _getNavBar()),

            ///tabbar
            Container(
              height: widget.tabHeight,
              color: widget.tabBgColor,
              child: Column(children: widget.tabChildren ?? []),
            ),
          ],
        ));
  }

  @override
  void initState() {
    super.initState();
    if (widget.isAutoFocus) {
      focusNode.requestFocus();
    } else {
      focusNode.unfocus();
    }
  }

  @override
  void dispose() {
    super.dispose();
    focusNode.dispose();
    timer?.cancel();
  }

  ///带图标标题
  Widget _iconTitle() => Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            widget.isIconTitle
                ? const Icon(Icons.query_builder)
                : const SizedBox(
                    width: 0,
                    height: 0,
                  ),
            Text(
              widget.title,
              style: TextStyle(color: widget.color, fontSize: widget.titleSize, fontWeight: FontWeight.w500, decoration: TextDecoration.none),
            )
          ],
        ),
      );

  ///拍照图标在右侧搜索框
  Widget _photoIconRightSearchInput() => Container(
        width: 300.w,
        height: 30.h,
        margin: EdgeInsets.only(left: _getLeftDistance(), top: 7.h),
        decoration: const BoxDecoration(
          color: Color.fromRGBO(248, 248, 248, 1),
          borderRadius: BorderRadius.all(Radius.circular(50)),
        ),
        child: Stack(
          children: [
            Container(
              width: 200.w,
              height: 30.h,
              margin: EdgeInsets.only(left: 10),
              child: CupertinoTextField(
                controller: widget.textEditingController,
                textInputAction: TextInputAction.search, // 将按钮文字改为“搜索”
                clearButtonMode: OverlayVisibilityMode.notEditing,
                readOnly: widget.isDisable,
                focusNode: focusNode,
                placeholder: widget.placeholder,
                placeholderStyle: const TextStyle(fontSize: 14),
                style: const TextStyle(fontSize: 12),
                onTap: () {
                  if (widget.routeName != '') {
                    focusNode.unfocus();
                    Get.toNamed(widget.routeName);
                  }
                },
                decoration: BoxDecoration(
                    // color: Colors.red
                    ),
                onChanged: (value) {
                  inputValue = value;
                  // timer?.cancel();
                  // timer = Timer(durationTime, () {
                  //   widget.onInput!(value);
                  // });
                },
                onEditingComplete: () {
                  logger.d('编辑完成');
                  focusNode.unfocus();
                  widget.onInput!(inputValue);
                },
              ),
            ),
            Positioned(top: 5.h, right: 20, child: Icon(Icons.camera_alt))
          ],
        ),
      );

  ///右侧为拍照和搜索按钮的搜索框
  Widget _photoSearchBtnRightInput() {
    return Container(
      width: 300.w,
      height: 30.h,
      margin: EdgeInsets.only(left: _getLeftDistance(), top: 7.h),
      decoration: const BoxDecoration(
        color: Color.fromRGBO(248, 248, 248, 1),
        // color: Colors.amber,
        borderRadius: BorderRadius.all(Radius.circular(50)),
      ),
      child: Stack(
        children: [
          Container(
            width: 290.w,
            height: 30.h,
            margin: const EdgeInsets.only(left: 0),
            child: CupertinoTextField(
              readOnly: widget.isDisable,
              controller: widget.textEditingController,
              textInputAction: TextInputAction.search, // 将按钮文字改为“搜索”
              placeholder: widget.placeholder,
              placeholderStyle: const TextStyle(fontSize: 14, color: ThemeConfig.subTextColor),
              style: const TextStyle(fontSize: 12),
              focusNode: focusNode,
              decoration: inputStyle(),
              onTap: () {
                if (widget.routeName != '') {
                  focusNode.unfocus();
                  Get.toNamed(widget.routeName);
                }
              },
              onChanged: (value) {
                inputValue = value;
                // timer?.cancel();
                // timer = Timer(durationTime, () {
                //   widget.onInput!(value);
                // });
              },
              onEditingComplete: () {
                logger.d('编辑完成');
                focusNode.unfocus();
                widget.onInput!(inputValue);
              },
            ),
          ),
          // Positioned(top: 5.h, right: 70, child: const Icon(Icons.camera_alt)),
          Positioned(
              top: 5.h,
              right: 10.w,
              child: BaseInteractive(
                childWidget: Container(
                  width: 50,
                  height: 20.h,
                  alignment: Alignment.center,
                  decoration: const BoxDecoration(color: ThemeConfig.themeColor, borderRadius: BorderRadius.all(Radius.circular(25))),
                  child: Text(
                    '搜索',
                    style: setTextStyle(13, FontWeight.w300, Colors.white),
                  ),
                ),
                onClick: () {
                  if (widget.onClickSearch != null) {
                    widget.onClickSearch!(inputValue);
                  }
                },
              ))
        ],
      ),
    );
  }

  ///左侧为放大镜图标的搜索框
  Widget _searchIconLeftSearchInput() => Container(
        width: 335.w,
        height: 32.h,
        margin: EdgeInsets.only(left: _getLeftDistance(), top: 7.h),
        decoration: const BoxDecoration(
          color: Color.fromRGBO(248, 248, 248, 1),
          // color: Colors.red,
          borderRadius: BorderRadius.all(Radius.circular(50)),
        ),
        child: Stack(
          children: [
            Container(
              margin: EdgeInsets.only(left: 10, top: 6.h),
              child: const Icon(
                Icons.search,
              ),
            ),
            Container(
              width: 275.w,
              height: 32.h,
              margin: const EdgeInsets.only(left: 43),
              child: CupertinoTextField(
                controller: widget.textEditingController,
                textInputAction: TextInputAction.search, // 将按钮文字改为“搜索”
                readOnly: widget.isDisable,
                focusNode: focusNode,
                placeholder: widget.placeholder,
                placeholderStyle: setTextStyle(13, FontWeight.w500, ThemeConfig.mainTextColor),
                style: const TextStyle(fontSize: 13),
                decoration: BoxDecoration(),
                onTap: () {
                  if (widget.routeName != '') {
                    focusNode.unfocus();
                    Get.toNamed(widget.routeName);
                  }
                },
                onChanged: (value) {
                  inputValue = value;
                  // timer?.cancel();
                  // timer = Timer(durationTime, () {
                  //   widget.onInput!(value);
                  // });
                },
                onEditingComplete: () {
                  logger.d('编辑完成');
                  focusNode.unfocus();
                  widget.onInput!(inputValue);
                },
              ),
            ),
          ],
        ),
      );

  ///获取搜索框
  Widget _getSearchInput() {
    switch (widget.searchType) {
      case SearchStyleType.none:
        return emptyWidget();
      case SearchStyleType.onlySearch:
        return _searchIconLeftSearchInput();
      case SearchStyleType.onlyPhoto:
        return _photoIconRightSearchInput();
      case SearchStyleType.photoSearchBtn:
        return _photoSearchBtnRightInput();
    }
  }

  ///计算输入框在左侧有图标和无图标时的间距
  double _getLeftDistance() {
    switch (widget.iconType) {
      case IconType.none:
        return 20;
      case IconType.back:
        return 66;
      case IconType.msg:
        return 20;
    }
  }

  ///返回按钮
  Widget _backIcon() {
    return Positioned(
        left: 7,
        top: 3.h,
        child: IconButton(
            onPressed: () {
              if (widget.beforeBack != null) {
                widget.beforeBack!();
                return;
              }
              Get.back();
            },
            icon: const Icon(
              Icons.arrow_back_ios_new_rounded,
              color: Colors.black,
            )));
  }

  ///菜单按钮
  Widget _menuIcon() {
    return Positioned(
        left: 50,
        top: 13.h,
        child: CustomPopup(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _createMenuItem('menu_index.png', '首页', () {
                Get.until((route) => Get.currentRoute == Routes.main);
              }),
              _createMenuItem('menu_search.png', '搜索', () {
                Navigator.pop(context);
                Get.toNamed(Routes.search);
              }),
              _createMenuItem('menu_user_center.png', '个人中心', () {
                Get.until((route) => Get.currentRoute == Routes.main);
                EventMgr.send(EventType.exchangeNav, 'my');
              }),
              _createMenuItem('menu_collect.png', '我的收藏', () {
                Navigator.pop(context);
                Get.toNamed(Routes.collect);
              }),
            ],
          ),
          child: const BaseIcon(
            url: 'menu.png',
          ),
        ));
  }

  ///创建菜单item
  Widget _createMenuItem(String url, String text, VoidCallback onClick) {
    return Padding(
        padding: EdgeInsets.only(bottom: 20.h),
        child: BaseInteractive(
          childWidget: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              BaseIcon(url: url),
              const SizedBox(
                width: 5,
              ),
              Text(
                text,
                style: setTextStyle(12, FontWeight.w400, ThemeConfig.mainTextColor),
              )
            ],
          ),
          onClick: onClick,
        ));
  }

  ///消息按钮
  Widget _msgIcon() {
    return Positioned(
        right: 0,
        top: 15.h,
        child: const BaseBadges(
          num: 16,
          child: BaseIcon(
            url: 'msg.png',
            color: Colors.white,
          ),
        ));
  }

  ///分享按钮
  Widget _shareIcon() {
    return Positioned(
        right: 10,
        top: 10.h,
        child: GestureDetector(
          onTap: () {
            if (widget.shareCallBack != null) {
              widget.shareCallBack!();
            }
          },
          child: const BaseIcon(
            url: 'fenxiang.png',
            color: Colors.black,
          ),
        ));
  }

  ///获取图标
  Widget _getIcon() {
    switch (widget.iconType) {
      case IconType.none:
        return emptyWidget();
      case IconType.back:
        return _backIcon();
      case IconType.msg:
        return _msgIcon();
    }
  }

  ///通用导航栏
  Widget commonNavBar() {
    return Container(
        width: double.infinity,
        height: 44.h,
        decoration: BoxDecoration(color: widget.navBgColor, border: widget.isShowNavBottomBorder ? const Border(bottom: BorderSide(color: Color.fromRGBO(0, 0, 0, 0.1))) : const Border()),
        child: Stack(
          children: [
            _getIcon(),
            widget.isShowMenuIcon ? _menuIcon() : emptyWidget(),
            widget.isSearch ? _getSearchInput() : _iconTitle(),
            if (widget.isShowShare) _shareIcon(),
          ],
        ));
  }

  ///自定义导航栏
  Widget customNavBar() {
    return Container(width: double.infinity, height: 44.h, decoration: BoxDecoration(color: widget.navBgColor, border: widget.isShowNavBottomBorder ? const Border(bottom: BorderSide(color: Color.fromRGBO(0, 0, 0, 0.1))) : const Border()), child: widget.customWidget);
  }

  ///获取导航栏
  Widget _getNavBar() {
    switch (widget.navType) {
      case NavType.decoration:
        return DecorationTopNavBar(
          info: widget.info,
        );
      case NavType.common:
        return commonNavBar();
      case NavType.custom:
        return customNavBar();
    }
  }
}

///图标类型枚举
enum IconType {
  ///不显示
  none,

  ///消息按钮(显示在右侧)
  msg,

  ///返回按钮
  back
}

///搜索框样式枚举
enum SearchStyleType {
  ///不带任何图标
  none,

  ///仅带搜索图标
  onlySearch,

  ///仅带拍照图标
  onlyPhoto,

  ///拍照和搜索按钮
  photoSearchBtn
}

///导航栏类型
enum NavType {
  ///通用
  common,

  ///装修
  decoration,

  ///自定义
  custom
}
